package com.tian.config;

import com.tian.enums.ChargeStationRabbitMQConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

/**
 * {@code @description:} 创建direct类型的交换机
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-03-24 10:20
 * {@code @version:} 1.0
 */
@Slf4j
@Scope("prototype")
@Configuration
public class RabbitMqConfig {

    //充电桩通信日志
    @Bean
    public Queue queueMessageGunCommunicateLog() {
        return new Queue(ChargeStationRabbitMQConstant.STATION_GUN_COM_LOG_QUEUE, true);
    }

    @Bean
    TopicExchange exchangeGunCommunicateLog() {
        return new TopicExchange(ChargeStationRabbitMQConstant.STATION_GUN_COM_LOG_EXCHANGE, true, false);
    }

    @Bean
    Binding bindingGunCommunicateLog(Queue queueMessageGunCommunicateLog, TopicExchange exchangeGunCommunicateLog) {
        return BindingBuilder.bind(queueMessageGunCommunicateLog).to(exchangeGunCommunicateLog).with(ChargeStationRabbitMQConstant.STATION_GUN_COM_LOG_ROUTING_KEY);
    }

    //test
    @Bean
    public Queue queueMessageTest() {
        return new Queue("charge.test.queue", true);
    }

    @Bean
    TopicExchange exchangeTest() {
        return new TopicExchange("charge.test.exchange", true, false);
    }

    @Bean
    Binding bindingExchangeMessageTest(Queue queueMessageTest, TopicExchange exchangeTest) {
        return BindingBuilder.bind(queueMessageTest).to(exchangeTest).with("charge.test.routingkey");
    }

    @Scope("prototype")
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        //设置消息投递失败的策略，有两种策略：自动删除或返回到客户端。
        //我们既然要做可靠性，当然是设置为返回到客户端(true是返回客户端，false是自动删除)
        rabbitTemplate.setMandatory(true);
        return rabbitTemplate;
    }
}

